package com.example.tianxi.yuexiuhhpatient.fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.tianxi.yuexiuhhpatient.EditHistoryInfoActivity;
import com.example.tianxi.yuexiuhhpatient.PatientInfoActivity;
import com.example.tianxi.yuexiuhhpatient.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link DoctorFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link DoctorFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class DoctorFragment extends Fragment implements View.OnClickListener{
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;


    public static final String TAG = "DoctorFragment";


    View view;

    List<String> group;           //组列表
    List<List<JSONObject>> child;     //子列表
    DoctorAdapter adapter;  //数据适配器

    ExpandableListView expandableListView ;//


    //新增通讯录按钮
    TextView more ;
    TextView title ;


//    private OnFragmentInteractionListener mListener;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment DoctorFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static DoctorFragment newInstance(String param1, String param2) {
        DoctorFragment fragment = new DoctorFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    public static DoctorFragment newInstance() {
        DoctorFragment fragment = new DoctorFragment();

        return fragment;
    }


    public DoctorFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

//        initView();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view =inflater.inflate(R.layout.fragment_doctor, container, false);

        initView();
        return view;
    }

    public void initView(){

        more = (TextView)view.findViewById(R.id.action);
        title = (TextView)view.findViewById(R.id.title);

        more.setText("+");
        more.setOnClickListener(this);
        title.setText("通讯录");

        expandableListView = (ExpandableListView)view.findViewById(R.id.expandablelistview);

        initData();
    }

    public void initData(){
        group = new ArrayList<String>();
        child = new ArrayList<List<JSONObject>>();

        addInfo("眼科",new String[]{"冯唐","男","138123***","GuangZhou,edf发给说的给对方地方的分割肉上的人更有人地方"});
        addInfo("耳鼻喉",new String[]{"木心","男","138123***","GuangZhou,edf发给说的给对方地方的分割肉上的人更有人地ou"});

        addInfo("胸外",new String[]{"陈丹青","男","138123***","ShenZhenou,edf发给说的给对方地方的分割肉上的人更有人地"});
        addInfo("内科",new String[]{"王鼎钧","男","138123***","ShangHaiou,edf发给说的给对方地方的分割肉上的人更有人地"});

        addInfo("脑科", new String[]{"蒙曼","女", "138231***", "ZhanJiangou,edf发给说的给对方地方的分割肉上的人更有人地"});

        expandableListView.setAdapter(new DoctorAdapter());
        expandableListView.setCacheColorHint(0);

        for (int i = 0; i < child.size(); i++) {
            expandableListView.expandGroup(i);
        }

        expandableListView.setOnChildClickListener(new GetOnClickListener());

    }

    /**
     * 模拟给组、子列表添加数据
     * @param g-group
     * @param c-child
     */
    private void addInfo(String g,String[] c){
        if(!group.contains(g))
            group.add(g);//仅作为测试数据使用，后期网络请求数据时候要重新设置

        List<JSONObject> childitem = new ArrayList<JSONObject>();
        JSONObject object =new JSONObject();
        try{
            for(int i=0;i<c.length;i++){
                object.put(String.valueOf(i), c[i]);
            }
        }catch (JSONException e){
        }
        childitem.add(object);
        childitem.add(object);
        childitem.add(object);
        childitem.add(object);
        childitem.add(object);
        childitem.add(object);
        childitem.add(object);

        child.add(childitem);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
//        if (mListener != null) {
//            mListener.onFragmentInteraction(uri);
//        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
//        try {
//            mListener = (OnFragmentInteractionListener) activity;
//        } catch (ClassCastException e) {
//            throw new ClassCastException(activity.toString()
//                    + " must implement OnFragmentInteractionListener");
//        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
//        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
//    public interface OnFragmentInteractionListener {
//        // TODO: Update argument type and name
//        public void onFragmentInteraction(Uri uri);
//    }


    class DoctorAdapter extends BaseExpandableListAdapter {


        //-----------------Child----------------//
        @Override
        public Object getChild(int groupPosition, int childPosition) {
            return child.get(groupPosition).get(childPosition);
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            return child.get(groupPosition).size();
        }

        @Override
        public View getChildView(int groupPosition, int childPosition,
                                 boolean isLastChild, View convertView, ViewGroup parent) {
            JSONObject object = child.get(groupPosition).get(childPosition);
            if (convertView == null) {
                LayoutInflater inflater = LayoutInflater.from(getActivity());
                convertView = inflater.inflate(R.layout.user_itemview, null);
            }
//            ImageView userImage = (ImageView)convertView.findViewById(R.id.userimage_item);
//            userImage.setImageResource(R.drawable.icon_account);
            final TextView userName = (TextView)convertView.findViewById(R.id.username_item);
            final TextView userInfo = (TextView)convertView.findViewById(R.id.userinfo_item);

            try {
                userName.setText(object.getString("0"));
                userInfo.setText(object.getString("1")+" "+object.getString("3"));
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return convertView;
        }

        //----------------Group----------------//
        @Override
        public Object getGroup(int groupPosition) {
            return group.get(groupPosition);
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public int getGroupCount() {
            return group.size();
        }

        @Override
        public View getGroupView(int groupPosition, boolean isExpanded,
                                 View convertView, ViewGroup parent) {
            String string = group.get(groupPosition);
            return getGenericView(2, convertView, string);
        }

        //创建组/子视图
        public View getGenericView(int flag,View convertView,String s) {
            // Layout parameters for the ExpandableListView
//            AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
//                    ViewGroup.LayoutParams.FILL_PARENT, 40);
//            TextView text = new TextView();
//            text.setLayoutParams(lp);
//            // Center the text vertically
//            text.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
//            // Set the text starting position
//            text.setPadding(36, 0, 0, 0);
//
//            text.setText(s);
//            text.setTextColor(0x000);
//            text.setBackgroundColor(0xe5e5e5);
//
//            return text;

            if (convertView == null) {
                LayoutInflater inflater = LayoutInflater.from(getActivity());
                convertView = inflater.inflate(R.layout.user_listview, null);
            }
            convertView.setClickable(true);
            TextView title = (TextView) convertView.findViewById(R.id.content_001);
            title.setText(s);

            return convertView;
        }



        @Override
        public boolean hasStableIds() {
            // TODO Auto-generated method stub
            return true;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            // TODO Auto-generated method stub
            return true;
        }

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.action:
                Toast.makeText(getActivity(), "扫描二维码添加好友", Toast.LENGTH_SHORT).show();
                break;

            default:
                break;

        }
    }

    class GetOnClickListener implements OnChildClickListener{

        @Override
        public boolean onChildClick(ExpandableListView parent, View v,
                                    int groupPosition, int childPosition, long id) {
//            try {
//                HttpUtil.doctorDetailHttpRequest(lists.get(groupPosition).get(childPosition).getString("userId"), new HttpHandler(getActivity()) {
//
//                    @Override
//                    public void onSuccess(String msg) {
//                        // TODO Auto-generated method stub
//                        Intent intent = new Intent(getActivity(), PatientInfoActivity.class);
//                        intent.putExtra("doctor", msg);
//                        getActivity().startActivity(intent);
//                    }
//                });
//            } catch (JSONException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }

            Intent intent = new Intent(getActivity(), PatientInfoActivity.class);
            JSONObject object = child.get(groupPosition).get(childPosition);

            try {
                intent.putExtra("cate",group.get(groupPosition));
                intent.putExtra("name",object.getString("0"));
                intent.putExtra("sex",object.getString("1"));
                intent.putExtra("tel",object.getString("2"));
                intent.putExtra("info",object.getString("3"));
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            getActivity().startActivity(intent);

            return false;
        }

    }



}
